package org.university.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.university.common.ApiResponse;
import org.university.entity.Department;
import org.university.exception.ResourceNotFoundException;
import org.university.service.DepartmentService;

import java.util.List;

/**
 * @Author ：3570023082@qq.com
 * @Date ：2025/9/11 22:47
 * @Description ：For study.
 */
@CrossOrigin
@RestController
@RequestMapping("/departments")
public class DepartmentController {

    private static final Logger LOGGER = LoggerFactory.getLogger(DepartmentController.class);
    // 允许字段
    private static final List<String> ALLOWED_FIELDS = List.of("deptId", "deptName", "deptLocation",
            "deptPhone", "deanName");
    private final DepartmentService departmentService;

    public DepartmentController(DepartmentService departmentService) {
        this.departmentService = departmentService;
    }

    /**
     * 获取学院信息分页
     *
     * @param page 页码
     * @param size 页面大小
     * @return 信息分页
     */
    @GetMapping
    public ResponseEntity<ApiResponse<Page<Department>>> getDepartment(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
//        LOGGER.info("查询学院：页码={}, 每页大小={}", page, size);
        Page<Department> departments = departmentService.findAll(PageRequest.of(page, size));
        return ApiResponse.success(departments);
    }

    /**
     * 根据ID查找学院
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Department>> getDepartmentById(@PathVariable Integer id) {
//        LOGGER.info("查询学院ID: {}", id);
        return departmentService.findById(id)
                .map(ApiResponse::success)
                .orElseThrow(() -> new ResourceNotFoundException("未找到id为：" + id + " 的学院"));
    }

    /**
     * 创建学院
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Department>> createDepartment(@RequestBody Department department) {
        LOGGER.info("创建学院ID: {}", department.getDeptId());
        Department newDepartment = departmentService.save(department);
        return ApiResponse.created(newDepartment);
    }

    /**
     * 更新学院信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Department>> updateDepartment(
            @PathVariable Integer id,
            @RequestBody Department department) {

        LOGGER.info("更新学院ID: {}", id);
        if (departmentService.findById(id).isEmpty()) {
            return ApiResponse.error(HttpStatus.NOT_FOUND, new String("未找到id为：" + id + " 的学院"));
        }
        department.setDeptId(id);
        Department updatedDepartment = departmentService.save(department);
        return ApiResponse.success(updatedDepartment);
    }

    /**
     * 删除学院
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteDepartment(@PathVariable Integer id) {
        LOGGER.info("删除学院ID: {}", id);
        if (departmentService.findById(id).isEmpty()) {
            return ApiResponse.error(HttpStatus.NOT_FOUND, new String("未找到id为：" + id + " 的学院"));
        }
        departmentService.deleteById(id);
        return ResponseEntity.ok().build();
    }

    /**
     * 根据学院id获取学生总数
     *
     * @param id
     * @return
     */
    @GetMapping("/count/{id}")
    public ResponseEntity<ApiResponse<Long>> getStudentCount(@PathVariable Integer id) {
        if (departmentService.findById(id).isEmpty()) {
            return ApiResponse.error(HttpStatus.NOT_FOUND, new String("未找到id为：" + id + " 的学院"));
        }
        long count = departmentService.getStudentCount(id);
        return ApiResponse.success(count);
    }
}
